package day17.udp2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class UdpUtils {
    public static String input() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("请输入:");
            return reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void sendMessage(DatagramSocket datagramSocket, String message, SocketAddress address) {
        byte[] data = message.getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, address);
        try {
            datagramSocket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SocketAddress buildAddress(int port, String host) {
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getByName(host);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        return new InetSocketAddress(inetAddress, port);
    }

    public static String receiveMessage(DatagramSocket datagramSocket) {
        byte[] data = new byte[1024];
        // 创建数据包
        DatagramPacket packet = new DatagramPacket(data, data.length);
        // udp接受数据包
        try {
            datagramSocket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String message = new String(data, 0, packet.getLength());
        return message;
    }
}
